// T.ext 为增强后的 t
// 解决对extend中的方法的依赖
(function(global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./index')) :
    typeof define === 'function' && define.amd ? define(['t'], factory) :
    global.t = factory(t);
}(this, function(t) {
  t.extend({
    parseQueryString: function(url) {
      var reg_url = /^[^?#]+\?([^#\s]+)#?/,
        reg_para = /([^&=]+)=([\w\W]*?)(&|$)/g, //g is very important
        arr_url = reg_url.exec(url),
        str_para,
        result,
        ret = {};
      if (arr_url && arr_url[1]) {
        str_para = arr_url[1];
      } else {
        str_para = url;
      }
      while ((result = reg_para.exec(str_para)) != null) {
        ret[result[1]] = decodeURIComponent(result[2]);
      }
      return ret;
    },
    formatQueryString: function(params) {
      var queryStrings = [];
      for (var key in params) {
        queryStrings.push(key + "=" + encodeURIComponent(params[key]));
      }
      return queryStrings.join("&");
    },
    parseSetCookie: function(setCookies) {
      const cookies = {};
      if (setCookies && setCookies.length > 0) {
        for (var i = 0; i < setCookies.length; i++) {
          const cookieAsArr = setCookies[i].split(";")[0].split("=");
          const cookieKey = cookieAsArr[0];
          const cookieVal = cookieAsArr[1];
          cookies[cookieKey] = cookieVal;
        }
      }
      return cookies;
    },
    resetSetCookies: function(setCookies, domain) {
      var newSetCookies = [];
      if (setCookies && setCookies.length > 0) {
        for (var i = 0; i < setCookies.length; i++) {
          var setCookie = setCookies[i];
          if (/Domain=.*;/i.test(setCookie)) {
            setCookie = setCookie.replace(/Domain=[^;]*/i, 'Domain=' + domain);
          } else {
            setCookie = setCookie + "; Domain=" + domain;
          }
          newSetCookies.push(setCookie);
        }
      }
      return newSetCookies;
    },
    parseCookie: function(cookie) {
      if (!cookie) return null;
      cookie = cookie.replace(/ /g, '');
      const cookieStrArr = cookie.split(";");
      var cookies = {};
      for (var i = 0; i < cookieStrArr.length; i++) {
        if (cookieStrArr[i]) {
          const cookieArr = cookieStrArr[i].split('=');
          cookies[cookieArr[0]] = cookieArr[1];
        }
      }
      return cookies;
    },
    formatCookie: function(cookies) {
      var cookie = "";
      var first = true;
      for (var key in cookies) {
        if (!first) {
          cookie += "; ";
        }
        cookie += (key + "=" + cookies[key]);
        first = false;
      }
      return cookie;
    },
    
  });
  return t;
}))